package MySQL::Query::Hints;

use strict;
use warnings;
use base qw(MySQL::Query::Base);

use SQL::Builder::UseIndex; 
use Carp;

sub add_straight_join {
      my ($self , $sql) = @_;
      if (ref $sql) {
            $sql->straight_join(1);
      } else {
            $sql =~ s/SELECT/SELECT STRAIGHT_JOIN/;
      }
      return $sql;
}

sub delete_straight_join {
      my ($self , $sql) = @_;
      if (ref $sql) {
      } else {
            $sql =~ s/ STRAIGHT_JOIN//;
      }
      return $sql;
}

sub add_use_index {
      my ($self , $sql , $table , $indexes) = @_;
      
      #print "$table -> $indexes\n";
      
      return unless ref $sql;
      
      my $index = SQL::Builder::UseIndex->new();
      $index->table($table);
      if (ref $indexes eq 'ARRAY') {
            $index->expr(join "," , @$indexes);
      } else {
            $index->expr($indexes);
      }
      
      my $joins = $sql->joins->list;
      foreach my $j (@$joins) {
            if ($j->left_table and $j->left_table eq $table) {
                  $j->hint->list_push($index);
            } elsif ($j->right_table eq $table) {
                  $j->hint->list_push($index);
            } else {
                  next;
            }
      }
      
      return $sql;
}

sub delete_use_index {
      my ($self , $sql , $table) = @_;
      
      $sql =~ s/$table USE INDEX\([^)]+\)/$table/;
      return $sql;
}

sub add_force_index {
      my ($self , $sql , $table , $indexes) = @_;
      
      my $add = 'FORCE INDEX(';
      ref $indexes eq 'ARRAY' ? ($add .= join " , " , @$indexes) : ($add .= $indexes);
      $add .= ')';
      
      $sql =~ s/(FROM.+)\s+\b$table\b\s+[^.]/$1 $table $add /;
      
      return $sql;
}

sub delete_force_index {
      my ($self , $sql , $table) = @_;
      
      $sql =~ s/$table FORCE INDEX\([^)]+\)/$table/;
      return $sql;
}

1;

=head1 NAME

MySQL::Query::Hints

=head1 SYNOPSIS
      
      Add / Remove MySQL hints
      
=head1 DESCRIPTION

=head1 METHODS

=head2 new()

=head2 add_straight_join

=head2 delete_straight_join

=head2 add_use_index

=head2 delete_use_index

=head2 add_force_index

=head2 delete_force_index
